//
//  SlipViewController.swift
//  test
//
//  Created by lishuai on 2018/7/23.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit
import Kingfisher

class SlipViewController: UIViewController {
    
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var menuView: UIView!
    @IBOutlet weak var shadeView: UIView!
    @IBOutlet weak var adView: UIView!
    @IBOutlet weak var asScrollView: UIScrollView!
    @IBOutlet weak var closeButton: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!
    
    var mainViewController: NavigationController?
    var menuViewController: HomePageViewController?
    
    var config: Config?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        menuView.isHidden = true
        
        setupTuia()
        Fence.fence()
        loadAd()
        loadConfig()
        fetchVersions()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // MARK: - custom method
    
    /// 检查版本
    func fetchVersions() {
        User.versions(success: { [weak self] info in
            guard let info = info else {
                return
            }
            
            if info.versionSn > UIDevice.current.appVersion() {
                switch info.forceFlag {
                case 1:
                    self?.alertWithCancelButton(
                        title: "温馨提示",
                        message: info.versionNote,
                        okTitle: "更新",
                        cancelTitle: "不更新",
                        okStyle: .default,
                        completion: {
                            UIApplication.shared.open(URL(string: info.downLoadurl)!)
                    })
                case 2:
                    self?.alert(
                        title: "温馨提示",
                        message: info.versionNote,
                        completion: {
                            //干掉用户本地登录信息
                            User.logout()
                            UIApplication.shared.open(URL(string: info.downLoadurl)!)
                    })
                default:break
                }
            }
        }) { message in
            XHProgressHUD.showError(message.msg)
        }
    }
    
    /// 设置推啊
    func setupTuia() {
        let onceKey = "ONCE_KEY"
        
        if !UserDefaults.standard.bool(forKey: onceKey) {
            UserDefaults.standard.set(true, forKey: onceKey)
            
            if let paste = UIPasteboard.general.string,
                let key = paste.components(separatedBy: "=").first, key == "tuia",
                let id = paste.components(separatedBy: "=").last {
                UserDefaults.standard.set(id, forKey: "tuia_id")
                let urlStr = "https://activity.tuia.cn/log/effect/v2?" +
                    "advertKey=DC4E2EA359BCE06357AF5A6939581A65" +
                    "&subType=2" +
                "&a_old=\(id)"
                let urls = NSURL(string: urlStr)!
                let request = NSURLRequest(url: urls as URL) as URLRequest
                
                let task = URLSession.shared.dataTask(with: request) { (data, res, error) in
                    
                }
                task.resume()//开始执行
            }
        }
    }
    
    /// 读取广告
    func loadAd() {
        Ad.ad(success: { [weak self] ad in
            if let ad = ad, ad.list.count > 0, let self = self {
                self.adView.isHidden = false
                self.asScrollView.isHidden = false
                self.closeButton.isHidden = false
                self.pageControl.isHidden = false
                
                self.pageControl.numberOfPages = ad.list.count
                
                let width = self.asScrollView.frame.size.width
                let height = self.asScrollView.frame.size.height
                self.asScrollView.contentSize = CGSize(width: width * CGFloat(ad.list.count), height: height)
                for (i, v) in ad.list.enumerated() {
                    let imageURL = URL(string: kImageServerName + v.imagePath)
                    
                    let button = UIButton(type: .custom)
                    button.frame = CGRect(x: width * CGFloat(i), y: 0, width: width, height: height)
                    button.kf.setImage(with: imageURL,
                                       for: .normal,
                                       placeholder: UIImage(named: "ad"))
                    button.layer.cornerRadius = 10.0
                    button.layer.masksToBounds = true
                    
                    button.addBlock(for: .touchUpInside, block: { sender in
                        if v.adURL != "" {
                            self.performSegue(withIdentifier: "webViewSegue", sender: v)
                        }
                    })
                    
                    self.asScrollView.addSubview(button)
                }
            }
        }) { message in
            p(message)
        }
    }
    
    /// 读取配置
    func loadConfig() {
        Config.getConfig(configParam: nil, success: { [weak self] config in
            self?.config = config
            if let vc = self?.mainViewController?.viewControllers.first as? MainViewController {
                vc.showGoButton()
            }
        }) { message in
            p(message)
        }
    }
    
    /// 隐藏菜单
    func hiddenMenu() {
        UIView.animate(withDuration: 0.25, animations: { [weak self] in
            if let self = self {
                self.menuView.frame.origin.x = -self.menuView.frame.size.width
                self.shadeView.alpha = 0.0
            }
        }) { [weak self] finish in
            if finish, let self = self {
                self.shadeView.isHidden = true
                self.menuView.isHidden = true
            }
        }
    }
    
    /// 显示菜单
    func showMenu() {
        menuView.frame.origin.x = -menuView.frame.size.width
        menuView.isHidden = false
        shadeView.alpha = 0.0
        shadeView.isHidden = false
        
        UIView.animate(withDuration: 0.25) { [weak self] in
            self?.menuView.frame.origin.x = 0
            self?.shadeView.alpha = 0.5
        }
    }
    
    // MARK: - Navigation
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "mainSegue" {
            mainViewController = segue.destination as? NavigationController
        } else if segue.identifier == "menuSegue" {
            menuViewController = segue.destination as? HomePageViewController
        } else if segue.identifier == "webViewSegue" {  //web
            if let nav = segue.destination as? UINavigationController,
                let vc = nav.viewControllers.first as? WebViewController,
                let shareInfo = sender as? Ad.Image {
                vc.page = Page.other(shareInfo)
            }
        }
    }
    
    // MARK: - IBAction
    
    @IBAction func tap(_ sender: UITapGestureRecognizer) {
        hiddenMenu()
    }
    
    @IBAction func swipe(_ sender: UISwipeGestureRecognizer) {
        hiddenMenu()
    }
    
    @IBAction func closeAdView(_ sender: UIButton) {
        adView.removeFromSuperview()
        asScrollView.removeFromSuperview()
        closeButton.removeFromSuperview()
        pageControl.removeFromSuperview()
    }
}

extension UIViewController {
    var slipViewController: SlipViewController? {
        get {
            let slip = UIApplication.shared.keyWindow?.rootViewController
            
            if let slip = slip as? SlipViewController {
                return slip
            }
            
            return nil
        }
    }
}

class MainPushSegue: UIStoryboardSegue {
    override func perform() {
        source.slipViewController?.hiddenMenu()
        let nav = source.slipViewController?.mainViewController
        nav?.pushViewController(destination, animated: true)
    }
}

// MARK: - UIScrollViewDelegate

extension SlipViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let current = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
        pageControl.currentPage = current
    }
}
